import java.util.HashMap;


public class Driver {
	public static void main(String[] args) {
		final int TESTS = 100;
		final int MAX_DIGEST_SIZE = 24;
		
		//--------------------------------------------------------------------
		//Second Pre-Image Attack
		for(int size = 1; size <= MAX_DIGEST_SIZE; size++) {
			int attempts = 0;
			for(int i = 0; i < TESTS; i++) {
				ToyHash toyHash = new ToyHash("SHA-1", size);
				int m1 = (int)(Math.random()*100000);
				int result = toyHash.digest(m1);
				int round = 0;
				int messageDigest = 0;
				while(result != (messageDigest)) {
					round++;
					if(round != m1) {
						messageDigest = toyHash.digest(round);
					}
				}
				attempts += round;
				if(i%10 == 0)
					System.out.print(". ");
			}
//			System.out.println("\nDigest Size: " + size + "\t\tAverage Attempts: " + attempts/TESTS);
			System.out.println("\n" + size + "\t" + attempts/TESTS);
		}
		
		//--------------------------------------------------------------------
		//Collision Attack
		System.out.println();
		for(int size = 1; size <= MAX_DIGEST_SIZE; size++) {
			int attempts = 0;
			for(int i = 0; i < TESTS; i++) {
				ToyHash toyHash = new ToyHash("SHA-1", size);
				HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
				int round = 0;
				
				boolean matched = false;
				do {
					round++;
					//Get a new key
					int message = (int)(Math.random()*10000000);
					while(map.containsKey(message)) {
						message = (int)(Math.random()*10000000);
					}
					
					int digest = toyHash.digest(message);
					
					//Check to see if digest is already in the list
					if(map.containsValue(digest)) {
						matched = true;
					}
					else {
						map.put(message, digest);
					}
						
					
				}while(!matched);
				attempts += round;
				if(i%10 == 0)
					System.out.print(". ");
			}
//			System.out.println("Digest Size: " + size + "\t\tAverage Attempts: " + attempts/TESTS);
			System.out.println("\n" + size + "\t" + attempts/TESTS);
		}
	}
}
